﻿using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;

/// <summary>
/// 音频播放器。由于只使用了一个播放源，只适用于简单场景
/// </summary>
public class SoundManager : GameFrameClassBase
{
    private static AudioSource s_AudioSource;
    private static Dictionary<string, AudioClip> s_AudioClips = new Dictionary<string, AudioClip>();

    public override UniTask InitAsync()
    {
        GameObject go = new GameObject(nameof(SoundManager));
        s_AudioSource = go.AddComponent<AudioSource>();
        GameObject.DontDestroyOnLoad(s_AudioSource);
        return new UniTask();
    }

    public static async void Play(string soundKey, SoundType soundType, float volume = 1f)
    {
        if (!s_AudioClips.TryGetValue(soundKey, out var sound))
        {
            sound = await Addressables.LoadAssetAsync<AudioClip>($"Sounds/{soundKey}.{soundType}");
            s_AudioClips.Add(soundKey, sound);
        }
        s_AudioSource.clip = sound;
        s_AudioSource.loop = true;
        s_AudioSource.volume = volume;
        s_AudioSource.Play();
    }

    public static void StopAll()
    {
        s_AudioSource.Stop();
    }

    public static async void PlayOneTime(string soundKey, SoundType soundType, float volume = 1f)
    {
        if (!s_AudioClips.TryGetValue(soundKey, out var sound))
        {
            sound = await Addressables.LoadAssetAsync<AudioClip>($"Sounds/{soundKey}.{soundType}");
            s_AudioClips.Add(soundKey, sound);
        }
        s_AudioSource.PlayOneShot(sound, volume);
    }
}

public enum SoundType
{
    wav,
    mp3
}